// pages/i/setting.js
const auth = require('../../utils/auth.js')
const UserService = require('../../services/user.js')
const CdnService = require('../../services/cdn.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLoggedIn: false,
        userInfo: null,
        loginReady: false,
        headimg: '',
        phone: '',
        nickname: '',
        sex: '',
        sexText: '',
        birthday: '',
        submitting: false,
        // 生日选择器相关
        showBirthdayPicker: false,
        currentDate: new Date().getTime(),
        minDate: new Date('1900-01-01').getTime(),
        maxDate: new Date().getTime()
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        await this.checkLoginStatusAndInit()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        if (this.data.loginReady) {
            await this.checkLoginStatusAndInit()
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async checkLoginStatusAndInit() {
        try {
            const loginStatus = await auth.checkLoginStatus()
            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                userInfo: loginStatus.userInfo,
                loginReady: true
            })
            if (loginStatus.isLoggedIn) {
                await this.loadUserInfo()
            }
        } catch (error) {
            this.setData({
                isLoggedIn: false,
                userInfo: null,
                loginReady: true
            })
        }
    },

    async loadUserInfo() {
        const res = await UserService.getUserInfo({ showLoading: true })
        if (res.success && res.data) {
            // 处理性别显示
            let sexText = '';
            if (res.data.sex !== undefined && res.data.sex !== null) {
                sexText = res.data.sex == 0 ? '女' : '男';
            }
            
            this.setData({
                userInfo: res.data,
                headimg: res.data.headimg || '',
                phone: res.data.phone || '',
                nickname: res.data.nickname || '',
                sex: res.data.sex !== undefined ? res.data.sex : '',
                sexText: sexText,
                birthday: res.data.birthday || ''
            },function(){
                auth.setUserInfo(res.data);
            })
        }
    },

    onInputChange(e) {
        const { field } = e.currentTarget.dataset
        this.setData({
            [field]: e.detail.value
        })
    },

    async bindChooseAvatar(e) {
        const { avatarUrl } = e.detail
        this.setData({
            userInfo: {
                ...this.data.userInfo,
                headimg_url: avatarUrl
            },
            headimg: avatarUrl
        },async function(){
            const cdnResult = await CdnService.getAliyunCredit();
            if(cdnResult.success){
                wx.showLoading({
                    title: '上传图片中...'
                });
            }

            let data = cdnResult.data;

            let ext = avatarUrl.split('.').pop() || 'jpg';
            let path = CdnService.generateFilePath('avatar',ext);
            const ossFormData = {
                key: path,  //上传文件名称
                policy: data.policy,   //表单域
                'x-oss-signature-version': data.x_oss_signature_version,    //指定签名的版本和算法
                'x-oss-credential': data.x_oss_credential,   //指明派生密钥的参数集
                'x-oss-date': data.x_oss_date,   //请求的时间
                'x-oss-signature': data.signature,   //签名认证描述信息
                'x-oss-security-token': data.security_token,  //安全令牌
                success_action_status: "200"  //上传成功后响应状态码
            };

            let url = 'https://cloud--score-static.oss-cn-beijing.aliyuncs.com';
            wx.uploadFile({
                url, // 替换为实际的上传接口
                filePath: avatarUrl,
                name: 'file',
                formData: ossFormData,
                success: (res) => {
                    try {
                        if(res.statusCode == 200 && res.errMsg == 'uploadFile:ok'){

                            this.setData({
                                headimg: ossFormData.key
                            })

                            wx.hideLoading();
                            wx.showToast({
                                title: '上传成功',
                                icon: 'success'
                            });
                            
                        }else{
                            wx.hideLoading();
                            wx.showToast({
                                title: res.errMsg,
                                icon: 'none'
                            });
                        }
                    } catch (error) {
                        wx.hideLoading();
                        wx.showToast({
                            title: '上传失败',
                            icon: 'none'
                        });
                    }
                },
                fail: (error) => {
                    wx.hideLoading();
                    wx.showToast({
                        title: '上传失败',
                        icon: 'none'
                    });
                }
            });
        })
    },


    async onGetPhoneNumber(e) {
        try {

            // 检查授权结果
            if (e.detail.errMsg !== 'getPhoneNumber:ok') {
                wx.showModal({
                    title: '授权失败',
                    content: '需要授权手机号才能继续使用',
                    showCancel: false
                })
                return
            }

            // 调用绑定手机号接口
            const bindResult = await UserService.updatePhone({
                code: e.detail.code,
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv
            })

            if (bindResult.success) {
                auth.setUserInfo(bindResult.data.user);
                // 绑定成功
                wx.showToast({
                    title: '更改成功',
                    icon: 'success'
                })
            }
        } catch (error) {
            this.setData({ loading: false })
        } finally {
            this.setData({ loading: false })
        }
    },

    async onSubmit() {
        if (this.data.submitting) return
        this.setData({ submitting: true })
        const { headimg, nickname, sex, birthday } = this.data
        const res = await UserService.updateUserProfile({ headimg, nickname, sex, birthday, showLoading: true })
        if (res.success) {
            wx.showToast({ title: '保存成功', icon: 'success' })
            // 更新本地userInfo
            await this.loadUserInfo()
        } else {
            wx.showToast({ title: res.message || '保存失败', icon: 'none' })
        }
        this.setData({ submitting: false })
    },

    toAddress() {
        wx.navigateTo({
            url: '/pages/i/address'
        })
    },

    /**
     * 性别选择
     */
    onSexSelect() {
        wx.showActionSheet({
            itemList: ['女', '男'],
            success: (res) => {
                const sexMap = ['女', '男'];
                const sexValue = res.tapIndex;
                this.setData({
                    sex: sexValue,
                    sexText: sexMap[sexValue]
                });
            }
        });
    },

    /**
     * 生日选择
     */
    onBirthdaySelect() {
        // 设置当前选中的日期
        let currentDate = this.data.currentDate;
        if (this.data.birthday) {
            currentDate = new Date(this.data.birthday).getTime();
        }
        
        this.setData({
            showBirthdayPicker: true,
            currentDate: currentDate
        });
    },

    /**
     * 生日选择器确认
     */
    onBirthdayConfirm(e) {
        const date = new Date(e.detail);
        const formattedDate = this.formatDate(date);
        
        this.setData({
            birthday: formattedDate,
            showBirthdayPicker: false
        });
    },

    /**
     * 生日选择器关闭
     */
    onBirthdayPickerClose() {
        this.setData({
            showBirthdayPicker: false
        });
    },

    /**
     * 格式化日期为 YYYY-MM-DD 格式
     */
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

})